import Pacman from '../js/Pacman.js';
import Ghost from '../js/Ghost.js';
const requestData = params => {
    return axios.get(`http://wechat.yxfwpt.com/api/h520200625/scoreGet`, {
        params: params
    })
}
var PacmanGame = function () {    
    this.map = null;
    this.layer = null;
    
    this.numDots = 0;
    this.TOTAL_DOTS = 0;
    this.score = 0;
    this.scoreText = null;
    
    this.pacman = null; 
    this.clyde = null;
    this.pinky = null;
    this.inky = null;
    this.blinky = null;
    this.ghosts = [];

    this.safetile = 37;
    this.gridsize =35;       
    this.threshold = 3;
    
    this.SPECIAL_TILES = [
        { x: 12, y: 11 },
        { x: 15, y: 11 },
        { x: 12, y: 23 },
        { x: 15, y: 23 }
    ];
    
    this.TIME_MODES = [
        {
            mode: "scatter",
            time: 7000
        },
        {
            mode: "chase",
            time: 10000
        },
        {
            mode: "scatter",
            time: 7000
        },
        {
            mode: "chase",
            time: 10000
        },
        {
            mode: "scatter",
            time: 5000
        },
        {
            mode: "chase",
            time: 10000
        },
        {
            mode: "scatter",
            time: 5000
        }
    ];
    this.changeModeTimer = 0;
    this.remainingTime = 0;
    this.currentMode = 0;
    this.isPaused = false;
    this.FRIGHTENED_MODE_TIME = 7000;
    
    this.ORIGINAL_OVERFLOW_ERROR_ON = true;
    this.DEBUG_ON = false;
    
    this.KEY_COOLING_DOWN_TIME = 250;
    this.lastKeyPressed = 0;
  
    this.game = window.game;
  
};

PacmanGame.prototype = {

    init: function () {
        localStorage.setItem('hasPlay', true);
        this.score = 0;
        this.scale.scaleMode = Phaser.ScaleManager.EXACT_FIT;
        // this.scale.pageAlignHorizontally = true;
        // this.scale.pageAlignVertically = true;

        Phaser.Canvas.setImageRenderingCrisp(this.game.canvas); // full retro mode, i guess ;)

        this.physics.startSystem(Phaser.Physics.ARCADE);
    },

    preload: function () {
        //  We need this because the assets are on Amazon S3
        //  Remove the next 2 lines if running locally
        //this.load.baseURL = 'http://files.phaser.io.s3.amazonaws.com/codingtips/issue005/';
        //this.load.crossOrigin = 'anonymous';

        this.load.image('score', 'assets/score.png');
        this.load.image('dot', 'assets/bean-35.png');
        this.load.image("pill", "assets/bean2-35.png");
        this.load.image("goods1", "assets/bean3-35.png");
        this.load.image("goods2", "assets/bean4-35.png");
        this.load.image("goods3", "assets/bean5-35.png");
        this.load.spritesheet('pacman', 'assets/player.png',64,64,2);
        this.load.image("boxer", "assets/boxer.png");
        this.load.image('tiles', 'assets/beanman-tiles.png');
        this.load.image('bg', 'assets/game_bg.png');
        this.load.tilemap('map', 'assets/beanman-map.json', null, Phaser.Tilemap.TILED_JSON);

        //  Needless to say, the beast was stoned... and the graphics are Namco (C)opyrighted
    },

    create: function () {
        var bg = this.add.image(0, 0,'bg')
        bg.scale.set(1.2,1.2)

        this.map = this.add.tilemap('map');
        this.map.addTilesetImage('hh', 'tiles');

        this.layer = this.map.createLayer('Pacman');

        this.dots = this.add.physicsGroup();
        this.numDots = this.map.createFromTiles(29, this.safetile, 'dot', this.layer, this.dots);
        this.TOTAL_DOTS = this.numDots;
        
        this.pills = this.add.physicsGroup();
        this.numPills = this.map.createFromTiles(12, this.safetile, "pill", this.layer, this.pills);

        this.goods = this.add.physicsGroup();
        this.map.createFromTiles(1, this.safetile, "goods2", this.layer, this.goods);
        this.map.createFromTiles(25, this.safetile, "goods1", this.layer, this.goods);
        this.map.createFromTiles(28, this.safetile, "goods3", this.layer, this.goods);
        this.numGoods = 3;
        //  The dots will need to be offset by 6px to put them back in the middle of the grid
        // this.dots.setAll('x', 6, false, false, 1);
        // this.dots.setAll('y', 6, false, false, 1);
        this.cursors = this.input.keyboard.createCursorKeys();
        //  Pacman should collide with everything except the safe tile
        this.map.setCollisionByExclusion([this.safetile], true, this.layer);

		// Our hero
        this.pacman = new Pacman(this, "pacman");

        // Score and debug texts
        this.scoreText = game.add.text(110, 1180, this.score, { fontSize: "40px", fill: "#fff" });
        this.super = game.add.text(183, 958, "Super Keep Running", { fontSize: "38px", fill: "#fff" });
        
        this.changeModeTimer = this.time.time + this.TIME_MODES[this.currentMode].time;
        
        // Ghosts
        this.pinky = new Ghost(this, "boxer", "pinky", {x:8, y:15}, Phaser.LEFT);
        this.clyde = new Ghost(this, "boxer", "clyde", {x:11, y:15}, Phaser.RIGHT);
        this.ghosts.push(this.clyde, this.pinky);

        var score = this.add.image(50, 1180,'score')
       
        this.judgeTouchDirection()
    },
    dogEatsDog: function(pacman, ghost) {
        this.killPacman();
        //得分接口
        requestData({
            socre: this.score,
            // userId: 微信授权获取
        }).then((res) => {
            if (res.data.data && res.data.data.length > 0) {
                this.jsonData = res.data.data
                game.state.start('score')
            }
        }).catch((e) => {
            alert('服务有问题，请刷新页面')
        })
    },
    getCurrentMode: function() {
        if (!this.isPaused) {
            if (this.TIME_MODES[this.currentMode].mode === "scatter") {
                return "scatter";
            } else {
                return "chase";
            }
        } else {
            return "random";
        }
    },      
    killPacman: function() {
        this.pacman.isDead = true;
        this.stopGhosts();
    },
    
    stopGhosts: function() {
        for (var i=0; i<this.ghosts.length; i++) {
            this.ghosts[i].mode = this.ghosts[i].STOP;
        }
    },

    update: function () {
        this.scoreText.text = this.score;
        
        if (!this.pacman.isDead) {
            for (var i=0; i<this.ghosts.length; i++) {
                if (this.ghosts[i].mode !== this.ghosts[i].RETURNING_HOME) {
                    this.physics.arcade.overlap(this.pacman.sprite, this.ghosts[i].ghost, this.dogEatsDog, null, this);
                }
            }
            if (this.changeModeTimer !== -1 && !this.isPaused && this.changeModeTimer < this.time.time) {
                this.currentMode++;
                if(this.currentMode === 5) this.currentMode =0;
                this.changeModeTimer = this.time.time + this.TIME_MODES[this.currentMode].time;
                if (this.TIME_MODES[this.currentMode].mode === "chase") {
                    this.sendAttackOrder();
                } else {
                    this.sendScatterOrder();
                }
                console.log("new mode:", this.TIME_MODES[this.currentMode].mode, this.TIME_MODES[this.currentMode].time);
            }
            if (this.isPaused && this.changeModeTimer < this.time.time) {
                this.changeModeTimer = this.time.time + this.remainingTime;
                this.isPaused = false;
                if (this.TIME_MODES[this.currentMode].mode === "chase") {
                    this.sendAttackOrder();
                } else {
                    this.sendScatterOrder();
                }
                console.log("new mode:", this.TIME_MODES[this.currentMode].mode, this.TIME_MODES[this.currentMode].time);
            }
        }
        
        this.pacman.update();
        this.updateGhosts();
        
        this.checkKeys();
    },    
    isSpecialTile: function(tile) {
        for (var q=0; q<this.SPECIAL_TILES.length; q++) {
            if (tile.x === this.SPECIAL_TILES[q].x && tile.y === this.SPECIAL_TILES[q].y) {
                return true;
            } 
        }
        return false;
    },
    
    updateGhosts: function() {
        for (var i=0; i<this.ghosts.length; i++) {
            this.ghosts[i].update();
        }
    }, 
    sendAttackOrder: function() {
        for (var i=0; i<this.ghosts.length; i++) {
            this.ghosts[i].attack();
        }
    },
    
    sendExitOrder: function(ghost) {
        ghost.mode = this.clyde.EXIT_HOME;
    },
    
    sendScatterOrder: function() {
        for (var i=0; i<this.ghosts.length; i++) {
            this.ghosts[i].scatter();
        }
    },
    judgeTouchDirection: function() {
        var startx, starty;
        var that = this;
        game.input.onDown.add(function(e) {
            startx = e.x;
            starty = e.y;
        });
        game.input.onUp.add(function(e) {
            var endx, endy;
            endx = e.x;
            endy = e.y;
            that.pacman.checkKeys(that.getDirection(startx, starty, endx, endy))
        });
    },
    getDirection: function(startx, starty, endx, endy){
        var angx = endx - startx;
        var angy = endy - starty;
        var result = 0;
        //如果滑动距离太短
        if (Math.abs(angx) < 2 && Math.abs(angy) < 2) {
            return result;
        }
        var angle = Math.atan2(angy, angx) * 180 / Math.PI;
        if (angle >= -135 && angle <= -45) {
            result = 1;
        } else if (angle > 45 && angle < 135) {
            result = 2;
        } else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) {
            result = 3;
        } else if (angle >= -45 && angle <= 45) {
            result = 4;
        }
 
        return result;
    },

    render: function() {
        if (this.DEBUG_ON) {
            for (var i=0; i<this.ghosts.length; i++) {
                var color = "rgba(0, 255, 255, 0.6)";
                switch (this.ghosts[i].name) {
                    case "blinky":
                        color = "rgba(255, 0, 0, 0.6";
                        break;
                    case "pinky":
                        color = "rgba(255, 105, 180, 0.6";
                        break;
                    case "clyde":
                        color = "rgba(255, 165, 0, 0.6";
                        break;
                }
                if (this.ghosts[i].ghostDestination) {
                    var x = this.game.math.snapToFloor(Math.floor(this.ghosts[i].ghostDestination.x), this.gridsize);
                    var y = this.game.math.snapToFloor(Math.floor(this.ghosts[i].ghostDestination.y), this.gridsize);
                    this.game.debug.geom(new Phaser.Rectangle(x, y, 16, 16), color);
                }
            }
            if (this.debugPosition) {
                this.game.debug.geom(new Phaser.Rectangle(this.debugPosition.x, this.debugPosition.y, 16, 16), "#00ff00");
            }
        }
    },

    checkKeys: function () {
        this.pacman.checkKeys(this.cursors);
    },
    
    
};
export default PacmanGame
